package com.weaver.seconddev.api.tl.service;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.weaver.common.hrm.util.HrmContextUtil;
import com.weaver.common.hrm.util.Util;
import com.weaver.eteams.file.client.file.FileData;
import com.weaver.eteams.file.client.file.FileObj;
import com.weaver.eteams.file.client.param.storage.info.FileStorageInfo;
import com.weaver.eteams.file.client.remote.FileClientService;
import com.weaver.file.ud.api.FileDownloadService;
import com.weaver.file.ud.rpc.storage.match.FileStoRuleMatchClient;
import com.weaver.file.ud.storage.match.StoRuleMatchDto;
import com.weaver.file.ud.storage.match.StoRuleMatchParam;
import com.weaver.framework.rpc.annotation.RpcReference;
import com.weaver.seconddev.api.tl.gr_api.EcologyCommonService2;
import com.weaver.seconddev.api.tl.gr_api.GrAttachmentPushAction;
import com.weaver.seconddev.api.tl.purchase_api.PoReqMessage;
import com.weaver.seconddev.api.tl.purchase_api.PurchaseOrderRsp;
import com.weaver.seconddev.api.tl.request.AttachmentsReq;
import com.weaver.seconddev.api.tl.request.GetUploadFileInfoReq;
import com.weaver.seconddev.api.tl.response.UploadFileInfoRsp;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import javax.annotation.Resource;
import java.util.*;

/**
 * SAPService
 *
 * @author tianhao
 * @date 15/04/2025 3:51 pm
 */
@org.springframework.stereotype.Service("tl_service_SAPCommonService")
public class SAPCommonService {


    public static final Logger logger_996e17f1 = LoggerFactory.getLogger(GrAttachmentPushAction.class);

    @RpcReference
    private FileClientService fileClientService;

    @RpcReference
    private FileStoRuleMatchClient fileStoRuleMatchClient;

    @Autowired
    private FileDownloadService fileDownloadService;

    @Resource(name = "tl_service_EcologyCommonService2")
    private EcologyCommonService2 ecologyCommonService2;


    /**
     * 调用SAP创建PO接口
     *
     * @param requestId
     * @param poReqMessage
     * @param createPoStatus
     * @param currentSupplierCode
     * @return
     */
    public Map<String, String> createPurchaseOrder(String requestId, PoReqMessage poReqMessage, String createPoStatus, String currentSupplierCode) {
        logger_996e17f1.error("RequestId:" + requestId + ",SupplierCode:" + currentSupplierCode + "======Start Call Create PO Interface======");
        String errorMessage = null;
        String purchaseOrder = null;
        String responseBody = null;
        try {
            //responseBody = EcologyCommonService2.callESBInterface("createPurchaseOrder", poReqMessage.getRequestBody());
            responseBody = EcologyCommonService2.callESBInterface("100613275897086090", poReqMessage.getRequestBody());
            PurchaseOrderRsp purchaseOrderRsp = JSON.parseObject(responseBody, PurchaseOrderRsp.class);
            logger_996e17f1.error("RequestId:" + requestId + ",SupplierCode:" + currentSupplierCode + ",purchaseOrderRsp:" + JSON.toJSONString(purchaseOrderRsp, SerializerFeature.WriteNullStringAsEmpty));
            // 获取Po号
            purchaseOrder = purchaseOrderRsp.getPurchaseOrder();
            if (StringUtils.isBlank(purchaseOrder)) {
                if (StringUtils.isNotBlank(purchaseOrderRsp.getErrorMessage())) {
                    errorMessage = purchaseOrderRsp.getErrorMessage();
                } else if (StringUtils.isNotBlank(purchaseOrderRsp.getMessage().getDetails())) {
                    errorMessage = purchaseOrderRsp.getMessage().getDetails();
                }
                createPoStatus = "0";
            }
        } catch (JSONException e) {
            createPoStatus = "0";
            // 如果报文解析失败，错误信息就记录原始报文
            errorMessage = responseBody;
        } catch (Exception e) {
            createPoStatus = "0";
            errorMessage = "Create PO Error Message:" + e;
            logger_996e17f1.error("RequestId:" + requestId + ",SupplierCode:" + currentSupplierCode + ",ErrorMessage:" + errorMessage, e);
        }
        Map<String, String> resultMap = new HashMap<>();
        resultMap.put("createPoStatus", createPoStatus);
        resultMap.put("purchaseOrder", purchaseOrder);
        resultMap.put("errorMessage", errorMessage);
        return resultMap;
    }

    /**
     * 上传附件
     *
     * @param requestId
     * @param purchaseOrder
     * @param attachmentId
     * @return
     */
    public String uploadAttachments(String requestId, String purchaseOrder, String attachmentId) {
        logger_996e17f1.info("RequestId:" + requestId + ",PurchaseOrder:" + purchaseOrder + "======Start Upload PO Attachments======AttachmentId:" + attachmentId);
        // 从服务器获取附件
        String[] attachmentArray = attachmentId.split(",");
        String errorMessage = null;
        // 多个附件循环处理，循环上传到oss
        for (int i = 0; i < attachmentArray.length; i++) {
            List<Integer> fileIdList = new ArrayList<>();
            long fileobjId = Util.getLongValue(attachmentArray[i],-1L);
            FileObj fileObj = fileClientService.getById(fileobjId);
            FileStorageInfo fileStorageInfo = null;
            if(fileObj.getUrl() != null ) {
                StoRuleMatchParam stoRuleMatchParam = new StoRuleMatchParam.ExactMatchBuilder()
                        .setStorageUrl(fileObj.getUrl()).setTenantKey(HrmContextUtil.getCurrentTenantKey()).build();
                StoRuleMatchDto stoRuleMatchDto = Optional.ofNullable(
                        fileStoRuleMatchClient.exactMatch(stoRuleMatchParam)).get();
                if (stoRuleMatchDto != null) {
                    fileStorageInfo = stoRuleMatchDto.getFileStorageInfo();
                }
            }
            if(fileObj != null ){
                String fileName = fileObj.getName();
                String url = fileObj.getUrl();
                // 获取附件的信息
                logger_996e17f1.info("RequestId:" + requestId + ",PurchaseOrder:" + purchaseOrder + ",Upload File Name:" + fileName + ",File_URL:" + url);
                // 获取附件上传预签名URL
                UploadFileInfoRsp uploadFileInfoRsp = getUploadFileInfo(requestId, purchaseOrder, Collections.singletonList(fileName));
                if (uploadFileInfoRsp.getData().isEmpty()) {
                    errorMessage = uploadFileInfoRsp.getErrorMessage();
                    if (StringUtils.isBlank(errorMessage)) {
                        errorMessage = "Get Upload File Url Info Error";
                    }
                    logger_996e17f1.error("RequestId:" + requestId + ",PurchaseOrder:" + purchaseOrder + ",ErrorMessage:" + errorMessage, new RuntimeException(errorMessage));
                    throw new RuntimeException(errorMessage);
                }
                try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
                    // 获取附件内容
                    /*    byte[] byteFileContent = FileUtil.zipToByteArray(fileRealPath);*/
                    FileData fileData = fileDownloadService.downloadFile(fileObj.getId());
                    byte[] byteFileContent = fileData.getData();
                    HttpPut put = new HttpPut(uploadFileInfoRsp.getData().get(0).getUploadPath());
                    // 将 byte[] 包装为 ByteArrayEntity
                    ByteArrayEntity entity = new ByteArrayEntity(byteFileContent);
                    put.setEntity(entity);

                    // 不要手动设置 Content-Type (除非预签名 URL 明确要求)
                    // 上传附件到OSS
                    logger_996e17f1.info("RequestId:" + requestId + ",PurchaseOrder:" + purchaseOrder + ",Upload File Name:" + fileName + "======Start Call Upload PO Attachments Interface======");
                    try (CloseableHttpResponse response = httpClient.execute(put)) {
                        logger_996e17f1.info("RequestId:" + requestId + ",PurchaseOrder:" + purchaseOrder + ",Upload File Name:" + fileName + "======Complete Call Upload PO Attachments Interface======");
                        int httpStatusCode = response.getStatusLine().getStatusCode();
                        String uploadRspBody = response.getEntity().toString();
                        logger_996e17f1.info("RequestId:" + requestId + ",PurchaseOrder:" + purchaseOrder + ",Upload File Name:" + fileName + ",Http Status Code:" + httpStatusCode + ",Purchase Upload Response:" + uploadRspBody);
                        if (httpStatusCode == 200) {
                            // 获取返回信息
                            fileIdList.add(uploadFileInfoRsp.getData().get(0).getFileId());
                        } else {
                            // 如果报文解析失败，错误信息就记录原始报文
                            try {
                                logger_996e17f1.info("Start Parse Error Message");
                                errorMessage = JSON.parseObject(uploadRspBody).getString("errorMessage");
                            } catch (JSONException e) {
                                logger_996e17f1.info("Response Message Parse Exception");
                                errorMessage = uploadRspBody;
                            }
                        }
                    }
                    // 上传PO附件
                    if (!fileIdList.isEmpty()) {
                        AttachmentsReq attachmentsReq = new AttachmentsReq(fileIdList, purchaseOrder);

                        // String responseBody = ecologyCommonService2.callESBInterface("attachments", JSON.toJSONString(attachmentsReq, SerializerFeature.WriteNullStringAsEmpty));
                        String responseBody = ecologyCommonService2.callESBInterface("100613275897086088", JSON.toJSONString(attachmentsReq, SerializerFeature.WriteNullStringAsEmpty));
                        logger_996e17f1.info("RequestId:" + requestId + ",PurchaseOrder:" + purchaseOrder + ",ResponseBody:" + responseBody);
                        if (StringUtils.isNotBlank(responseBody)) {
                            JSONObject jsonObject = JSON.parseObject(responseBody);
                            String result = jsonObject.getString("body");
                            if ("success".equals(result)) {
                                errorMessage = result;
                            } else {
                                if (StringUtils.isNotBlank(jsonObject.getString("message"))) {
                                    errorMessage = jsonObject.getString("message");
                                } else if (StringUtils.isNotBlank(jsonObject.getString("errorMessage"))) {
                                    errorMessage = jsonObject.getString("errorMessage");
                                }
                            }
                        } else {
                            logger_996e17f1.info("responseBody:" + responseBody + ",responseBody is null");
                            errorMessage = "Upload PO Attachments Error:responseBody is null";
                            throw new RuntimeException(errorMessage);
                        }
                    }
                } catch (Exception e) {
                    errorMessage = "Upload PO Attachments Error Message:" + e;
                    logger_996e17f1.error("RequestId:" + requestId + ",PurchaseOrder:" + purchaseOrder + ",Upload File Name:" + fileName + ",ErrorMessage:" + errorMessage, e);
                }
            }

        }
        logger_996e17f1.info("RequestId:" + requestId + ",PurchaseOrder:" + purchaseOrder + "======Complete Upload PO Attachments======errorMessage：" + errorMessage);

        return errorMessage;
    }


    /**
     * 获取上传附件信息
     *
     * @param requestId
     * @param purchaseOrder
     * @param fileNameList
     * @return
     */
    public UploadFileInfoRsp getUploadFileInfo(String requestId, String purchaseOrder, List<String> fileNameList) {
        logger_996e17f1.info("RequestId:" + requestId + "======Start Get Upload File Info======PurchaseOrder:" + purchaseOrder + ",fileNameList:" + fileNameList);
        UploadFileInfoRsp uploadFileInfoRsp = null;
        try {
            GetUploadFileInfoReq getUploadFileInfoReq = new GetUploadFileInfoReq(purchaseOrder, fileNameList);
            //String responseBody = ecologyCommonService2.callESBInterface("getUploadFileInfo", JSON.toJSONString(getUploadFileInfoReq, SerializerFeature.WriteNullStringAsEmpty));
            String responseBody = ecologyCommonService2.callESBInterface("100613275897086094", JSON.toJSONString(getUploadFileInfoReq, SerializerFeature.WriteNullStringAsEmpty));
            uploadFileInfoRsp = JSON.parseObject(responseBody, UploadFileInfoRsp.class);
        } catch (Exception e) {
            logger_996e17f1.info("RequestId:" + requestId + ",PurchaseOrder:" + purchaseOrder + ",ErrorMessage:" + e.getMessage(), e);
        }
        logger_996e17f1.info("RequestId:" + requestId + ",PurchaseOrder:" + purchaseOrder + "======Complete Get Upload File Info======uploadFIleInfoRsp:" + JSON.toJSONString(uploadFileInfoRsp, SerializerFeature.WriteNullStringAsEmpty));
        return uploadFileInfoRsp;
    }

}
